import 'dart:io';
import 'dart:convert';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:get/get.dart';
import 'logger_service.dart';

/// 偏好设置服务 - Preferences Service
/// 负责管理应用的键值对设置存储
/// Manages key-value pair settings storage for the application
class PreferencesService extends GetxService {
  static PreferencesService get to => Get.find();

  // 存储文件路径 - Storage file path
  late String _preferencesFilePath;
  
  // 内存中的偏好设置缓存 - In-memory preferences cache
  final Map<String, dynamic> _preferences = {};

  @override
  Future<void> onInit() async {
    super.onInit();
    await _initializePreferences();
  }

  /// 初始化偏好设置 - Initialize Preferences
  /// Sets up the preferences file and loads existing settings
  /// 设置偏好设置文件并加载现有设置
  Future<void> _initializePreferences() async {
    try {
      // 获取应用数据目录 - Get application data directory
      Directory appDir;
      
      if (Platform.isAndroid || Platform.isIOS) {
        final documentsDir = await getApplicationDocumentsDirectory();
        appDir = Directory(path.join(documentsDir.path, 'Prompt'));
      } else if (Platform.isWindows) {
        final userProfile = Platform.environment['USERPROFILE'] ?? 'C:\\Users\\Administrator';
        final documentsPath = path.join(userProfile, 'Documents');
        appDir = Directory(path.join(documentsPath, 'PromptFlie'));
      } else {
        appDir = Directory.current;
      }

      // 确保目录存在 - Ensure directory exists
      if (!await appDir.exists()) {
        await appDir.create(recursive: true);
      }

      _preferencesFilePath = path.join(appDir.path, 'preferences.json');
      
      // 加载现有偏好设置 - Load existing preferences
      await _loadPreferences();
      
      LoggerService.info('偏好设置服务初始化完成 - PreferencesService initialized');
    } catch (e) {
      LoggerService.error('偏好设置服务初始化失败 - PreferencesService initialization failed', error: e);
      rethrow;
    }
  }

  /// 加载偏好设置 - Load Preferences
  /// Loads preferences from the JSON file into memory
  /// 从JSON文件加载偏好设置到内存中
  Future<void> _loadPreferences() async {
    try {
      final file = File(_preferencesFilePath);
      if (await file.exists()) {
        final content = await file.readAsString();
        final data = json.decode(content) as Map<String, dynamic>;
        _preferences.clear();
        _preferences.addAll(data);
      }
    } catch (e) {
      LoggerService.error('加载偏好设置失败 - Failed to load preferences', error: e);
    }
  }

  /// 保存偏好设置 - Save Preferences
  /// Saves the current preferences to the JSON file
  /// 将当前偏好设置保存到JSON文件
  Future<void> _savePreferences() async {
    try {
      final file = File(_preferencesFilePath);
      await file.writeAsString(json.encode(_preferences));
    } catch (e) {
      LoggerService.error('保存偏好设置失败 - Failed to save preferences', error: e);
    }
  }

  /// 获取字符串值 - Get String Value
  /// Retrieves a string value from preferences
  /// 从偏好设置中获取字符串值
  Future<String?> getString(String key) async {
    return _preferences[key] as String?;
  }

  /// 设置字符串值 - Set String Value
  /// Stores a string value in preferences
  /// 在偏好设置中存储字符串值
  Future<void> setString(String key, String value) async {
    _preferences[key] = value;
    await _savePreferences();
  }

  /// 获取布尔值 - Get Boolean Value
  /// Retrieves a boolean value from preferences
  /// 从偏好设置中获取布尔值
  Future<bool?> getBool(String key) async {
    return _preferences[key] as bool?;
  }

  /// 设置布尔值 - Set Boolean Value
  /// Stores a boolean value in preferences
  /// 在偏好设置中存储布尔值
  Future<void> setBool(String key, bool value) async {
    _preferences[key] = value;
    await _savePreferences();
  }

  /// 获取整数值 - Get Integer Value
  /// Retrieves an integer value from preferences
  /// 从偏好设置中获取整数值
  Future<int?> getInt(String key) async {
    return _preferences[key] as int?;
  }

  /// 设置整数值 - Set Integer Value
  /// Stores an integer value in preferences
  /// 在偏好设置中存储整数值
  Future<void> setInt(String key, int value) async {
    _preferences[key] = value;
    await _savePreferences();
  }

  /// 获取双精度浮点数值 - Get Double Value
  /// Retrieves a double value from preferences
  /// 从偏好设置中获取双精度浮点数值
  Future<double?> getDouble(String key) async {
    return _preferences[key] as double?;
  }

  /// 设置双精度浮点数值 - Set Double Value
  /// Stores a double value in preferences
  /// 在偏好设置中存储双精度浮点数值
  Future<void> setDouble(String key, double value) async {
    _preferences[key] = value;
    await _savePreferences();
  }

  /// 获取字符串列表 - Get String List
  /// Retrieves a list of strings from preferences
  /// 从偏好设置中获取字符串列表
  Future<List<String>?> getStringList(String key) async {
    final value = _preferences[key];
    if (value is List) {
      return value.cast<String>();
    }
    return null;
  }

  /// 设置字符串列表 - Set String List
  /// Stores a list of strings in preferences
  /// 在偏好设置中存储字符串列表
  Future<void> setStringList(String key, List<String> value) async {
    _preferences[key] = value;
    await _savePreferences();
  }

  /// 删除键值对 - Remove Key-Value Pair
  /// Removes a key-value pair from preferences
  /// 从偏好设置中删除键值对
  Future<void> remove(String key) async {
    _preferences.remove(key);
    await _savePreferences();
  }

  /// 检查键是否存在 - Check if Key Exists
  /// Checks if a key exists in preferences
  /// 检查偏好设置中是否存在某个键
  bool containsKey(String key) {
    return _preferences.containsKey(key);
  }

  /// 获取所有键 - Get All Keys
  /// Returns all keys in preferences
  /// 返回偏好设置中的所有键
  Set<String> getKeys() {
    return _preferences.keys.toSet();
  }

  /// 清空所有偏好设置 - Clear All Preferences
  /// Removes all preferences
  /// 清空所有偏好设置
  Future<void> clear() async {
    _preferences.clear();
    await _savePreferences();
  }

  /// 获取偏好设置的副本 - Get Preferences Copy
  /// Returns a copy of all preferences
  /// 返回所有偏好设置的副本
  Map<String, dynamic> getAll() {
    return Map<String, dynamic>.from(_preferences);
  }
}